

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="https://gitee.com/wang-xuwen/wxwvaldz/raw/master/img/网站logo.png">
  <link rel="icon" href="https://gitee.com/wang-xuwen/wxwvaldz/raw/master/img/网站logo.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="Mysql中的查询数据以及修改数据语法">
  <meta name="author" content="小王">
  <meta name="keywords" content="Blog">
  <meta name="description" content="Mysql中的查询数据以及修改数据语法">
<meta property="og:type" content="article">
<meta property="og:title" content="Mysql初学习(1)">
<meta property="og:url" content="http://wang-xuwen.gitee.io/wang-xuwen.gitee.io/2021/12/20/Mysql%E5%88%9D%E5%AD%A6-1/index.html">
<meta property="og:site_name" content="菠萝头&#39;Blog">
<meta property="og:description" content="Mysql中的查询数据以及修改数据语法">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-12-20T10:55:12.000Z">
<meta property="article:modified_time" content="2021-12-21T07:31:29.259Z">
<meta property="article:author" content="wxwvaldz">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="点滴记录">
<meta name="twitter:card" content="summary_large_image">
  
  <title>Mysql初学习(1) - 菠萝头&#39;Blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"wang-xuwen.gitee.io","root":"/","version":"1.8.12","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":1280684234,"leancloud":{"app_id":"JOpFiJtO4MLP5D7U1ojf6Ja3-gzGzoHsz","app_key":"2EinzSUFSXLtr3xK7WRCnpJL","server_url":null,"path":"window.location.pathname"}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>菠萝头&#39;Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('https://gitee.com/wang-xuwen/wxwvaldz/raw/master/img/v2-39b206355387a08c5c86d3a6e41bb84f_r.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="Mysql初学习(1)">
              
            </span>

            
              <div class="mt-3">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-author" aria-hidden="true"></i>
      小王
    </span>
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-12-20 18:55" pubdate>
        2021年12月20日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      6k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      19 分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-page-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-page-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Mysql初学习(1)</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：2 个月前
                
              </p>
            
            <div class="markdown-body">
              <p>Mysql中的查询数据以及修改数据语法</p>
<span id="more"></span>

<hr>
<h2 id="查询数据"><a href="#查询数据" class="headerlink" title="查询数据"></a>查询数据</h2><h3 id="基本查询"><a href="#基本查询" class="headerlink" title="基本查询"></a>基本查询</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT * FROM students;<br></code></pre></td></tr></table></figure>

<p>使用<code>SELECT * FROM students</code>时，<code>SELECT</code>是关键字，表示将要执行一个查询，<code>*</code>表示“所有列”，<code>FROM</code>表示将要从哪个表查询，本例中是<code>students</code>表。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT 100+200;<br></code></pre></td></tr></table></figure>

<h3 id="条件查询"><a href="#条件查询" class="headerlink" title="条件查询"></a>条件查询</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT * FROM students WHERE score &gt;=80;<br></code></pre></td></tr></table></figure>

<p>SELECT语句可以通过<code>WHERE</code>条件来设定查询条件，查询结果是满足查询条件的记录。例如，要指定条件“分数在80分或以上的学生”，写成<code>WHERE</code>条件就是<code>SELECT * FROM students WHERE score &gt;= 80</code>。</p>
<p>其中，<code>WHERE</code>关键字后面的<code>score &gt;= 80</code>就是条件。<code>score</code>是列名，该列存储了学生的成绩，因此，<code>score &gt;= 80</code>就筛选出了指定条件的记录：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT * FROM &lt;表名&gt; WHERE &lt;条件表达式&gt;<br></code></pre></td></tr></table></figure>

<p>俩条件同时成立</p>
<p>score &gt;= 80 AND gender = ‘M’</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT * FROM students WHERE score &gt;= 80 AND gender = &#x27;M&#x27;;<br></code></pre></td></tr></table></figure>

<p>俩条件满足其一：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT * FROM students WHERE score &gt;= 80 OR gender = &#x27;M&#x27;;<br></code></pre></td></tr></table></figure>

<p>不满足该条件：（不常用）</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT * FROM students WHERE NOT class_id = 2;<br><br>SELECT * FROM students WHERE (score &lt; 80 OR score &gt; 90) AND gender = &#x27;M&#x27;;<br></code></pre></td></tr></table></figure>

<p>加括号可以改变其优先级，not优先级最高</p>
<table>
<thead>
<tr>
<th align="left">条件</th>
<th align="left">表达式举例1</th>
<th align="left">表达式举例2</th>
<th align="left">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="left">使用=判断相等</td>
<td align="left">score = 80</td>
<td align="left">name = ‘abc’</td>
<td align="left">字符串需要用单引号括起来</td>
</tr>
<tr>
<td align="left">使用&gt;判断大于</td>
<td align="left">score &gt; 80</td>
<td align="left">name &gt; ‘abc’</td>
<td align="left">字符串比较根据ASCII码，中文字符比较根据数据库设置</td>
</tr>
<tr>
<td align="left">使用&gt;=判断大于或相等</td>
<td align="left">score &gt;= 80</td>
<td align="left">name &gt;= ‘abc’</td>
<td align="left"></td>
</tr>
<tr>
<td align="left">使用&lt;判断小于</td>
<td align="left">score &lt; 80</td>
<td align="left">name &lt;= ‘abc’</td>
<td align="left"></td>
</tr>
<tr>
<td align="left">使用&lt;=判断小于或相等</td>
<td align="left">score &lt;= 80</td>
<td align="left">name &lt;= ‘abc’</td>
<td align="left"></td>
</tr>
<tr>
<td align="left">使用&lt;&gt;判断不相等</td>
<td align="left">score &lt;&gt; 80</td>
<td align="left">name &lt;&gt; ‘abc’</td>
<td align="left"></td>
</tr>
<tr>
<td align="left">使用LIKE判断相似</td>
<td align="left">name LIKE ‘ab%’</td>
<td align="left">name LIKE ‘%bc%’</td>
<td align="left">%表示任意字符，例如’ab%’将匹配’ab’，’abc’，’abcd’</td>
</tr>
</tbody></table>
<h3 id="投影查询"><a href="#投影查询" class="headerlink" title="投影查询"></a>投影查询</h3><p>我们只想返回一个表中的某几列数据</p>
<p>例如，从<code>students</code>表中返回<code>id</code>、<code>score</code>和<code>name</code>这三列：</p>
<p>SELECT id, score, name FROM students;</p>
<p>投影时还可以将投影的列名更改</p>
<p>它的语法是<code>SELECT 列1 别名1, 列2 别名2, 列3 别名3 FROM ...</code>。</p>
<p>例如，以下<code>SELECT</code>语句将列名<code>score</code>重命名为<code>points</code>，而<code>id</code>和<code>name</code>列名保持不变：</p>
<p>SELECT id, score points, name FROM students;</p>
<h3 id="排序"><a href="#排序" class="headerlink" title="排序"></a>排序</h3><p>我们使用SELECT进行查询时，数据库通常使用主键排序，如果我们想按照其他条件排序</p>
<p>如果我们要根据其他条件排序怎么办？可以加上<code>ORDER BY</code>子句。例如按照成绩从低到高进行排序：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT id, name, gender, score FROM students ORDER BY score;<br><br>SELECT id, name, gender, score FROM students ORDER BY score DESC;<br></code></pre></td></tr></table></figure>

<p>（加上DESC表示倒叙）</p>
<p>如果score列有相同的数据，进一步按照其他列排序使用<code>ORDER BY score DESC, gender</code>表示先按<code>score</code>列倒序，如果有相同分数的，再按<code>gender</code>列排序：</p>
<p>SELECT id, name, gender, score FROM students ORDER BY score DESC, gender;</p>
<p>如果有<code>WHERE</code>子句，那么<code>ORDER BY</code>子句要放到<code>WHERE</code>子句后面。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT id, name, gender, score<br>FROM students<br>WHERE class_id = 1<br>ORDER BY score DESC;<br></code></pre></td></tr></table></figure>

<h3 id="分页查询"><a href="#分页查询" class="headerlink" title="分页查询"></a>分页查询</h3><p>如果数据比较多，需要分页显示</p>
<p>这个查询可以通过<code>LIMIT &lt;M&gt; OFFSET &lt;N&gt;</code>子句实现。    </p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT id, name, gender, score<br>FROM students<br>ORDER BY score DESC<br>LIMIT 3 OFFSET 0;<br></code></pre></td></tr></table></figure>

<p>上述查询<code>LIMIT 3 OFFSET 0</code>表示，对结果集从0号记录开始，最多取3条。注意SQL记录集的索引从0开始。</p>
<p>如果要查询第2页，那么我们只需要“跳过”头3条记录，也就是对结果集从3号记录开始查询，把<code>OFFSET</code>设定为3：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT id, name, gender, score<br>FROM students<br>ORDER BY score DESC<br>LIMIT 3 OFFSET 3;<br></code></pre></td></tr></table></figure>

<p><code>OFFSET</code>是可选的，如果只写<code>LIMIT 15</code>，那么相当于<code>LIMIT 15 OFFSET 0</code>。</p>
<p>在MySQL中，<code>LIMIT 15 OFFSET 30</code>还可以简写成<code>LIMIT 30, 15</code>。</p>
<p>使用<code>LIMIT &lt;M&gt; OFFSET &lt;N&gt;</code>分页时，随着<code>N</code>越来越大，查询效率也会越来越低。</p>
<h3 id="聚合查询"><a href="#聚合查询" class="headerlink" title="聚合查询"></a>聚合查询</h3><p>查找一共有多少条记录</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT COUNT(*) FROM students;<br></code></pre></td></tr></table></figure>

<p><code>COUNT(*)</code>表示查询所有列的行数，要注意聚合的计算结果虽然是一个数字，但查询的结果仍然是一个二维表，只是这个二维表只有一行一列，并且列名是<code>COUNT(*)</code>。</p>
<p>设置别名</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT COUNT(*) num FROM students;<br></code></pre></td></tr></table></figure>

<p><code>COUNT(*)</code>和<code>COUNT(id)</code>实际上是一样的效果。</p>
<table>
<thead>
<tr>
<th align="left">函数</th>
<th align="left">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="left">SUM</td>
<td align="left">计算某一列的合计值，该列必须为数值类型</td>
</tr>
<tr>
<td align="left">AVG</td>
<td align="left">计算某一列的平均值，该列必须为数值类型</td>
</tr>
<tr>
<td align="left">MAX</td>
<td align="left">计算某一列的最大值</td>
</tr>
<tr>
<td align="left">MIN</td>
<td align="left">计算某一列的最小值</td>
</tr>
</tbody></table>
<p>注意，<code>MAX()</code>和<code>MIN()</code>函数并不限于数值类型。如果是字符类型，<code>MAX()</code>和<code>MIN()</code>会返回排序最后和排序最前的字符。</p>
<p>要特别注意：如果聚合查询的<code>WHERE</code>条件没有匹配到任何行，<code>COUNT()</code>会返回0，而<code>SUM()</code>、<code>AVG()</code>、<code>MAX()</code>和<code>MIN()</code>会返回<code>NULL</code>：</p>
<p>如果要统计多个班的数据</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT COUNT(*) num FROM students GROUP BY class_id;<br></code></pre></td></tr></table></figure>

<p>执行这个查询，<code>COUNT()</code>的结果不再是一个，而是3个，这是因为，<code>GROUP BY</code>子句指定了按<code>class_id</code>分组，因此，执行该<code>SELECT</code>语句时，会把<code>class_id</code>相同的列先分组，再分别计算，因此，得到了3行结果。</p>
<p>但是这3行结果分别是哪三个班级的，不好看出来，所以我们可以把<code>class_id</code>列也放入结果集中：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT class_id, COUNT(*) num FROM students GROUP BY class_id;<br></code></pre></td></tr></table></figure>

<p>也可以使用多个列进行分组。例如，我们想统计各班的男生和女生人数：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT class_id, gender, COUNT(*) num FROM students GROUP BY class_id, gender;<br></code></pre></td></tr></table></figure>

<h3 id="多表查询"><a href="#多表查询" class="headerlink" title="多表查询"></a>多表查询</h3><p>查询多个表的数据</p>
<p>例如，同时从<code>students</code>表和<code>classes</code>表的“乘积”，即查询数据，可以这么写：</p>
<p>查询多张表的语法是：<code>SELECT * FROM &lt;表1&gt; &lt;表2&gt;</code>。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT * FROM students, classes;<br></code></pre></td></tr></table></figure>

<p>它表示两个表两两乘在一起，行的总数是两个表的行数相乘</p>
<p>如果两个表有列的名字相同则可以给他们起别名</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT<br>    students.id sid,<br>    students.name,<br>    students.gender,<br>    students.score,<br>    classes.id cid,<br>    classes.name cname<br>FROM students, classes;<br></code></pre></td></tr></table></figure>

<p>也可这也设置</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT<br>    s.id sid,<br>    s.name,<br>    s.gender,<br>    s.score,<br>    c.id cid,<br>    c.name cname<br>FROM students s, classes c;<br></code></pre></td></tr></table></figure>

<p>也可以添加条件</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT<br>    s.id sid,<br>    s.name,<br>    s.gender,<br>    s.score,<br>    c.id cid,<br>    c.name cname<br>FROM students s, classes c<br>WHERE s.gender = &#x27;M&#x27; AND c.id = 1;<br></code></pre></td></tr></table></figure>

<h3 id="连接查询"><a href="#连接查询" class="headerlink" title="连接查询"></a>连接查询</h3><p>先查询所有学生的数据</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT s.id, s.name, s.class_id, s.gender, s.score FROM students s;<br></code></pre></td></tr></table></figure>

<p>利用班级id查询班级名字</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT s.id, s.name, s.class_id, c.name class_name, s.gender, s.score<br>FROM students s<br>INNER JOIN classes c<br>ON s.class_id = c.id;<br></code></pre></td></tr></table></figure>

<ol>
<li>先确定主表，仍然使用<code>FROM &lt;表1&gt;</code>的语法；</li>
<li>再确定需要连接的表，使用<code>INNER JOIN &lt;表2&gt;</code>的语法；</li>
<li>然后确定连接条件，使用<code>ON &lt;条件...&gt;</code>，这里的条件是<code>s.class_id = c.id</code>，表示<code>students</code>表的<code>class_id</code>列与<code>classes</code>表的<code>id</code>列相同的行需要连接；</li>
<li>可选：加上<code>WHERE</code>子句、<code>ORDER BY</code>等子句。</li>
</ol>
<p>外连接</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT s.id, s.name, s.class_id, c.name class_name, s.gender, s.score<br>FROM students s<br>RIGHT OUTER JOIN classes c<br>ON s.class_id = c.id;<br></code></pre></td></tr></table></figure>

<p>区别：如果class.id中只有1，2，3而c.id有1，2，3，4则外连接会显示id为4的数据，而其他数据全为null，内连接则不会出现这一行</p>
<p>INNER JOIN</p>
<p>LEFT OUTER JOIN</p>
<p>RIGHT OUTER JOIN</p>
<p>FULL OUTER JOIN</p>
<p>指向那一边就会把哪一边多出来的数据列出来</p>
<p>JOIN查询仍然可以使</p>
<p>可用<code>WHERE</code>条件和<code>ORDER BY</code>排序。</p>
<h2 id="修改数据"><a href="#修改数据" class="headerlink" title="修改数据"></a>修改数据</h2><h3 id="INSERT"><a href="#INSERT" class="headerlink" title="INSERT"></a>INSERT</h3><p>基本语法为：INSERT INTO &lt;表名&gt; (字段1, 字段2, …) VALUES (值1, 值2, …);</p>
<p>例如，我们向<code>students</code>表插入一条新记录，先列举出需要插入的字段名称，然后在<code>VALUES</code>子句中依次写出对应字段的值：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs mysql">INSERT INTO students (class_id, name, gender, score) VALUES (2, &#x27;大牛&#x27;, &#x27;M&#x27;, 80);<br>-- 查询并观察结果:<br>SELECT * FROM students;<br></code></pre></td></tr></table></figure>

<p>字段顺序一定要和数值得对应顺序一致，字段得顺序不一定要和数据表中字段顺序一致</p>
<p>可一次性添加多个记录</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs mysql">INSERT INTO students (class_id, name, gender, score) VALUES<br>  (1, &#x27;大宝&#x27;, &#x27;M&#x27;, 87),<br>  (2, &#x27;二宝&#x27;, &#x27;M&#x27;, 81);<br><br>SELECT * FROM students;<br></code></pre></td></tr></table></figure>

<h3 id="UPDATE"><a href="#UPDATE" class="headerlink" title="UPDATE"></a>UPDATE</h3><p>跟新字段数据，基本语法：UPDATE &lt;表名&gt; SET 字段1=值1, 字段2=值2, … WHERE …;</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs mysql">UPDATE students SET name=&#x27;大牛&#x27;, score=66 WHERE id=1;<br>-- 查询并观察结果:<br>SELECT * FROM students WHERE id=1;<br></code></pre></td></tr></table></figure>

<p>where条件实际上和select语句得条件是一样的，所以完全可以一次性跟新多条记录</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs mysql">UPDATE students SET name=&#x27;小牛&#x27;, score=77 WHERE id&gt;=5 AND id&lt;=7;<br>-- 查询并观察结果:<br>SELECT * FROM students;<br></code></pre></td></tr></table></figure>

<p>在update得语句中也可以使用表达式</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs mysql">UPDATE students SET score=score+10 WHERE score&lt;80;<br>-- 查询并观察结果:<br>SELECT * FROM students;<br></code></pre></td></tr></table></figure>

<p>如果where语句未匹配到任何字段，不会报错也不会有任何得数据跟新</p>
<p>注意，如果没有任何where语句，那么跟新得是表中得所有数据，所以在跟新数据之前最好先用select语句测试where条件是否筛选除了数据集</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">UPDATE students SET score=60;<br></code></pre></td></tr></table></figure>

<ul>
<li>在使用mysql这类真正得关系数据库进行跟新数据时，会返回跟新得行数以及where条件匹配的行数</li>
</ul>
<p>例如，更新<code>id=1</code>的记录时：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs mysql">mysql&gt; UPDATE students SET name=&#x27;大宝&#x27; WHERE id=1;<br>Query OK, 1 row affected (0.00 sec)<br>Rows matched: 1  Changed: 1  Warnings: 0<br></code></pre></td></tr></table></figure>

<p>当更新<code>id=999</code>的记录时：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs mysql">mysql&gt; UPDATE students SET name=&#x27;大宝&#x27; WHERE id=999;<br>Query OK, 0 rows affected (0.00 sec)<br>Rows matched: 0  Changed: 0  Warnings: 0<br></code></pre></td></tr></table></figure>

<p>MySQL会返回<code>0</code>，可以从打印的结果<code>Rows matched: 0 Changed: 0</code>看到</p>
<h3 id="DELETE"><a href="#DELETE" class="headerlink" title="DELETE"></a>DELETE</h3><p>DELETE语句的基本语法是：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">DELETE FROM &lt;表名&gt; WHERE ...;<br></code></pre></td></tr></table></figure>

<p>删除id=1的数据：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs mysql">DELETE FROM students WHERE id=1;<br>-- 查询并观察结果:<br>SELECT * FROM students;<br></code></pre></td></tr></table></figure>

<p>当然也可以使用where语句一次性删除多条记录</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs mysql">DELETE FROM students WHERE id&gt;=5 AND id&lt;=7;<br>-- 查询并观察结果:<br>SELECT * FROM students;<br></code></pre></td></tr></table></figure>

<p>和跟新数据相同，如果where语句未匹配到任何数据，则不会有任何数据删除</p>
<p>若未使用where语句，则会删除掉所有数据表中的数据</p>
<p>在使用MySQL这类真正的关系数据库时，<code>DELETE</code>语句也会返回删除的行数以及<code>WHERE</code>条件匹配的行数。</p>
<p>例如，分别执行删除<code>id=1</code>和<code>id=999</code>的记录：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs mysql">mysql&gt; DELETE FROM students WHERE id=1;<br>Query OK, 1 row affected (0.01 sec)<br><br>mysql&gt; DELETE FROM students WHERE id=999;<br>Query OK, 0 rows affected (0.01 sec)<br></code></pre></td></tr></table></figure>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a>
                    
                      <a class="hover-with-bg" href="/tags/%E7%82%B9%E6%BB%B4%E8%AE%B0%E5%BD%95/">点滴记录</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载先请联系作者且注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/12/21/Mysql%E5%88%9D%E5%AD%A6-2/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Mysql初学习(2)</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/12/10/%E8%8F%A0%E8%90%9D%E5%A4%B4%E7%9A%84%E5%8D%9A%E5%AE%A2%E8%AF%9E%E7%94%9F%E5%95%A6%EF%BC%81/">
                        <span class="hidden-mobile">菠萝头的博客诞生啦！</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                
  <div id="waline"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#waline', function() {
      Fluid.utils.createScript('https://cdn.jsdelivr.net/npm/@waline/client@1/dist/Waline.min.js', function() {
        var options = Object.assign(
          {"serverURL":"https://blog-api-fawn.vercel.app/","path":"window.location.pathname","placeholder":"想说的话~","meta":["nick","mail","link"],"requiredMeta":["nick"],"lang":"zh-CN","emoji":["https://cdn.jsdelivr.net/gh/walinejs/emojis/weibo"],"dark":"html[data-user-color-scheme=\"dark\"]","avatar":"retro","avatarCDN":"https://seccdn.libravatar.org/avatar/","avatarForce":false,"wordLimit":0,"pageSize":10,"highlight":true},
          {
            el: '#waline',
            path: window.location.pathname
          }
        )
        new Waline(options);
        Fluid.utils.waitElementVisible('#waline .vcontent', () => {
          Fluid.plugins.initFancyBox('#waline .vcontent img:not(.vemoji)');
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
    <!--  <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a>  -->
    <div>
      <span id="timeDate">载入天数...</span>
      <span id="times">载入时分秒...</span>
      <script>
      var now = new Date();
      function createtime(){
          var grt= new Date("12/9/2021 20:13:49");//此处修改你的建站时间或者网站上线时间
          now.setTime(now.getTime()+250);
          days = (now - grt ) / 1000 / 60 / 60 / 24;
          dnum = Math.floor(days);
          hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum);
          hnum = Math.floor(hours);
          if(String(hnum).length ==1 ){
              hnum = "0" + hnum;
          }
          minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
          mnum = Math.floor(minutes);
          if(String(mnum).length ==1 ){
                    mnum = "0" + mnum;
          }
          seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
          snum = Math.round(seconds);
          if(String(snum).length ==1 ){
                    snum = "0" + snum;
          }
          document.getElementById("timeDate").innerHTML = "🚀 &nbsp此博客网站已经在夹缝中生存了"+"<br/>"+dnum+"&nbsp天";  //此次自定义显示内容
          document.getElementById("times").innerHTML = hnum + "&nbsp小时&nbsp" + mnum + "&nbsp分&nbsp" + snum + "&nbsp秒";
      }  //此次自定义显示内容
      setInterval("createtime()",250);
      </script>
    </div>
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- LeanCloud 统计PV -->
        <span id="leancloud-site-pv-container" style="display: none">
            总访问量 
            <span id="leancloud-site-pv"></span>
             次
          </span>
      
      
        <!-- LeanCloud 统计UV -->
        <span id="leancloud-site-uv-container" style="display: none">
            总访客数 
            <span id="leancloud-site-uv"></span>
             人
          </span>
      

    
  </div>


  

  
    <!-- cnzz Analytics Icon -->
    <span id="cnzz_stat_icon_1280684234" style="display: none"></span>
  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  




  <script defer src="/js/leancloud.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>












  

  

  

  

  

  
    <!-- cnzz Analytics -->
    <script defer src="//s4.cnzz.com/z_stat.php?id=1280684234&show=pic"
            type="text/javascript"></script>
  





<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/assets/koharu.model.json"},"display":{"position":"left","width":150,"height":300,"hOffset":0,"vOffset":-20},"mobile":{"show":true},"react":{"opacity":1},"log":false});</script></body>
</html>
